package _interview75;

import java.util.ArrayList;
import java.util.List;

/**
 * 216. 组合总和 III
 */
public class No216 {
    private List<List<Integer>> ans;
    private List<Integer> path;
    private int k;
    private int sum;

    /**
     * 1. 枚举选哪个
     */
    public List<List<Integer>> combinationSum31(int k, int n) {
        ans = new ArrayList<>();
        path = new ArrayList<>();
        this.k = k;
        this.sum = n;
        dfs(9, 0);
        return ans;
    }

    private void dfs(int i, int curSum) {
        if (path.size() == k && curSum == sum) {
            ans.add(new ArrayList<>(path));
            return;
        }
        if (i == 0 || curSum > sum) return;

        for (int j = i; j > 0; j--) {
            path.add(j);
            dfs(j - 1, curSum + j);
            path.remove(path.size() - 1);
        }
    }

    /**
     * 2. 选或不选
     */
    public List<List<Integer>> combinationSum32(int k, int n) {
        ans = new ArrayList<>();
        path = new ArrayList<>();
        this.k = k;
        this.sum = n;
        dfs2(9, 0);
        return ans;
    }

    private void dfs2(int i, int curSum) {
        if (path.size() == k && curSum == sum) {
            ans.add(new ArrayList<>(path));
            return;
        }
        if (i == 0 || curSum > sum) return;
        // 选
        path.add(i);
        dfs2(i - 1, curSum + i);
        path.remove(path.size() - 1);

        // 不选
        dfs2(i - 1, curSum);
    }
}
